package zmee.pmas.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.OrmLocaleValue;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.IFormView;
import kd.bos.form.control.TreeEntryGrid;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.pmgt.pmas.formplugin.budget.BudgetBillPlugin;
import kd.pmgt.pmbs.business.helper.FileAttachmentHelper;
import kd.pmgt.pmbs.common.enums.BudgetSourceTypeEnum;
import kd.pmgt.pmbs.common.utils.BudgetEntryOperateHelper;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;

public class OutBudgetBillPlugin extends BudgetBillPlugin {
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        Object adjustId = this.getView().getFormShowParameter().getCustomParam("adjustId");
        Object projectId = this.getView().getFormShowParameter().getCustomParam("projectId");
        this.getModel().setValue("project", projectId);
        DynamicObject projectObj = (DynamicObject)this.getModel().getValue("project");
        String projectName = "";
        if (projectObj != null) {
            projectName = ((OrmLocaleValue)projectObj.get("name")).getLocaleValue();
            this.getModel().setValue("group", projectObj.get("group"));
        }

        Object sourceType = this.getModel().getValue("sourcetype");
        String formName = null;
        if (BudgetSourceTypeEnum.OUT.getValue().equals(sourceType)) {
            formName = ResManager.loadKDString("支出预算", "BudgetBillPlugin_5", "pmgt-pmas-formplugin", new Object[0]);
        } else if (BudgetSourceTypeEnum.IN.getValue().equals(sourceType)) {
            formName = ResManager.loadKDString("收入预算", "BudgetBillPlugin_6", "pmgt-pmas-formplugin", new Object[0]);
        }

        if (adjustId == null) {
            this.getModel().setValue("type", "NEW");
            BigDecimal version = ((BigDecimal)this.getModel().getValue("version")).setScale(1);
            this.getModel().setValue("name", String.format("%s-%s%s", projectName, formName, version.toPlainString()));
            Date curBillDate = (Date)this.getModel().getValue("year");
            if (curBillDate != null) {
                LocalDate localDate = curBillDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                try {
                    this.getModel().setValue("year", sdf.parse(localDate.getYear() + "-01-01"));
                } catch (ParseException var17) {
                    this.getView().showErrorNotification(ResManager.loadKDString("日期转换错误，请联系管理员处理。", "BudgetBillPlugin_44", "pmgt-pmas-formplugin", new Object[0]));
                }
            }
        } else {
            this.getModel().setValue("id", ORM.create().genLongId(this.getModel().getDataEntityType()));
            this.getModel().setValue("type", "ADJUST");
            DynamicObject adjust;
            if (BudgetSourceTypeEnum.OUT.getValue().equals(sourceType)) {
                adjust = BusinessDataServiceHelper.loadSingle(adjustId, "pmas_outbudget");
            } else {
                adjust = BusinessDataServiceHelper.loadSingle(adjustId, "pmas_inbudget");
            }

            BigDecimal newversion = adjust.getBigDecimal("version").add(BigDecimal.ONE).setScale(1);
            BigDecimal amount = adjust.getBigDecimal("totalamount");
            BigDecimal presamount = adjust.getBigDecimal("presamount");
            this.getModel().setValue("prevamount", amount);
            this.getModel().setValue("presamount", presamount);
            this.getModel().setValue("totalamount", amount);
            this.getModel().setValue("schangeamount", amount.subtract(presamount));
            this.getModel().setValue("budgetstage", adjust.get("budgetstage"));
            this.getModel().setValue("version", newversion);
            this.getModel().setValue("name", String.format("%s-%s%s", projectName, formName, newversion.toPlainString()));
            this.getModel().setValue("year", adjust.get("year"));
            DynamicObjectCollection entries = adjust.getDynamicObjectCollection("treeentryentity");
            this.getModel().deleteEntryData("treeentryentity");
            if (entries != null && entries.size() > 0) {
                this.fillTreeEntryByEntryEntity(entries, false, true, this.getView(), "treeentryentity", "budgetitemname", "descriptionentry", "budgetitem");
            }

            String sourceBillFormId = adjust.getDynamicObjectType().toString();
            Object sourceBillId = adjust.getPkValue();
            String destinationFormId = this.getView().getFormShowParameter().getFormId();
            Object destinationBillId = this.getModel().getDataEntity().getPkValue();
            FileAttachmentHelper.copyFileFromAToB(sourceBillFormId, sourceBillId, "attachmentpanel", destinationFormId, destinationBillId, "attachmentpanel");
        }

        this.setAmountEnable();
        this.setCurrency(projectObj);
    }
    private void setAmountEnable() {
            BudgetEntryOperateHelper.setAmountColumnEnable("treeentryentity", "budgetamount", this.getView());
            BudgetEntryOperateHelper.setTotalAmountEnable(this.getView(), "treeentryentity", "totalamount");
        }
    private void setCurrency(DynamicObject project) {
            if (project != null) {
                DynamicObject[] pros = BusinessDataServiceHelper.load("pmas_pro_approval", "id,currencyfield", new QFilter[]{new QFilter("pro", "=", project.getPkValue())});
                if (pros.length > 0) {
                    this.getModel().setValue("currency", pros[0].get("currencyfield"));
                }
            }

        }
    public void fillTreeEntryByEntryEntity(DynamicObjectCollection entryEntity, boolean isTemplateEntry, boolean isAdjust, IFormView formView, String fillEntryId, String budgetNameId, String descriptionId, String budgetItemId) {
        if (entryEntity != null && !entryEntity.isEmpty()) {
            IDataModel dataModel = formView.getModel();
            DynamicObjectCollection entryDatas = dataModel.getEntryEntity(fillEntryId);
            DynamicObjectType dt = entryDatas.getDynamicObjectType();
            HashMap<Long, Long> mapedNewPk = new HashMap(16);
            ORM orm = ORM.create();
            long[] newIds = orm.genLongIds(dt, entryEntity.size());
            int index = 0;
            Iterator var15 = entryEntity.iterator();

            DynamicObject entry;
            while(var15.hasNext()) {
                entry = (DynamicObject)var15.next();
                mapedNewPk.put((Long)entry.getPkValue(), newIds[index++]);
            }

            var15 = entryEntity.iterator();

            while(var15.hasNext()) {
                entry = (DynamicObject)var15.next();
                DynamicObject newTreeEntryData = new DynamicObject(dt);
                DynamicObject budgetItem;
                if (isTemplateEntry) {
                    newTreeEntryData.set(budgetNameId, entry.get("budgetitemname"));
                    newTreeEntryData.set(descriptionId, entry.get("descriptionentry"));
                    budgetItem = entry.getDynamicObject("budgetitem");
                    if (budgetItem != null) {
                        newTreeEntryData.set(budgetItemId, budgetItem);
                    }
                } else {
                    newTreeEntryData.set("budgetitemname", entry.get("budgetitemname"));
                    newTreeEntryData.set("descriptionentry", entry.get("descriptionentry"));
                    if (isAdjust) {
                        BigDecimal prevamount = (BigDecimal)entry.get("budgetamount");
                        newTreeEntryData.set("viamount", prevamount);
                        newTreeEntryData.set("isprev", Boolean.TRUE);
                        newTreeEntryData.set("budgetamount", prevamount);
                        newTreeEntryData.set("amountfield", prevamount);
                        newTreeEntryData.set("budgetamoney",entry.getBigDecimal("budgetamoney"));
                        BigDecimal siamount = (BigDecimal)entry.get("siamount");
                        if (BigDecimal.ZERO.compareTo(siamount) != 0) {
                            newTreeEntryData.set("siamount", siamount);
                            newTreeEntryData.set("ispres", Boolean.TRUE);
                        }
                    } else {
                        newTreeEntryData.set("siamount", entry.get("budgetamount"));
                        if (BigDecimal.ZERO.compareTo(entry.getBigDecimal("budgetamount")) != 0) {
                            newTreeEntryData.set("ispres", Boolean.TRUE);
                        } else {
                            newTreeEntryData.set("ispres", Boolean.FALSE);
                        }

                        newTreeEntryData.set("budgetamount", entry.get("budgetamount"));
                    }

                    budgetItem = entry.getDynamicObject("budgetitem");
                    if (budgetItem != null) {
                        newTreeEntryData.set("budgetitem", budgetItem);
                    }

                    DynamicObject projectBudgetItem = entry.getDynamicObject("projectbudgetitem");
                    if (projectBudgetItem != null) {
                        newTreeEntryData.set("projectbudgetitem", projectBudgetItem);
                    } else {
                        projectBudgetItem = BusinessDataServiceHelper.loadSingle(entry.getLong("id"), "pmas_projectbudget");
                        newTreeEntryData.set("projectbudgetitem", projectBudgetItem);
                    }
                }

                Long pid = (Long)entry.get("pid");
                Long newpid = 0L;
                if (pid != null && !pid.equals(0L)) {
                    newpid = (Long)mapedNewPk.get(pid);
                }

                newTreeEntryData.set("pid", newpid);
                newTreeEntryData.set("id", mapedNewPk.get(entry.getPkValue()));
                entryDatas.add(newTreeEntryData);
            }

            dataModel.updateEntryCache(entryDatas);
            TreeEntryGrid treeEntryGrid = (TreeEntryGrid)formView.getControl(fillEntryId);
            treeEntryGrid.setCollapse(false);
            formView.updateView(fillEntryId);
        }
    }
}
